<template>
    <div style="height: 100%; width: 1024px; color: #606266;
        font-size: 12px; margin: 0 auto; margin-top: 30px;">

        <el-steps :active="activeStep" simple style="margin-bottom: 10px;">
            <el-step title="购物车"/>
            <el-step title="订单确认"/>
            <el-step title="支付"/>
        </el-steps>

        <div v-if="activeStep === 0">
            <div class="talbe-title">
                <div class="talbe-title-item" style="width: 50px;">
                    <el-checkbox v-model="allChecked" @change="allCheckedChange"/>
                    全部
                </div>
                <div class="talbe-title-item" style="width: calc(100% - 450px);">商品</div>
                <div class="talbe-title-item" style="width: 100px;">单价（元）</div>
                <div class="talbe-title-item" style="width: 120px;">数量</div>
                <div class="talbe-title-item" style="width: 100px;">小记（元）</div>
                <div class="talbe-title-item" style="width: 80px;">操作</div>
            </div>

            <div v-for="(item, index) in shopCarList"
                :key="index" class="talbe-content">
                <div class="talbe-content-item" style="width: 50px;">
                    <el-checkbox v-model="item.display" @change="itemChange"/>
                </div>
                <div class="talbe-content-item" style="width: calc(100% - 450px);">
                    <el-image :src="item.image" fit="fill"
                        style="width: 80px; height: 80px; float: left;"/>
                    <div style="float: left; margin-left: 20px; width: calc(100% - 80px - 20px)">{{item.name}}</div>
                </div>
                <div class="talbe-content-item" style="width: 100px;">
                    {{item.price}}
                </div>
                <div class="talbe-content-item" style="width: 120px;">
                    <el-input-number v-model="item.num" @change="(val, val2)=> { numberChange(val, val2, item) }"
                        :min="1" size="mini" style="width: 100px;"/>
                </div>
                <div class="talbe-content-item" style="width: 100px;">
                    {{totalPrice(item)}}
                </div>
                <div class="talbe-content-item" style="width: 80px;">
                    <el-button type="text" size="mini" @click="del(item)">删除</el-button>
                </div>
            </div>

            <div class="car-operation">
                <div style="float: left; padding: 0 10px;">
                    <el-checkbox v-model="allChecked" style="margin-top: 15px;"
                    @change="allCheckedChange"/> 全选

                    <el-button style="margin-left: 20px;" size="mini"
                        type="text" @click="batchDel">删除选中商品</el-button>
                    <el-button size="mini" type="text">移到我的关注</el-button>
                    <el-button size="mini" type="text"
                        @click="clearCat">清空购物车</el-button>
                </div>
                <div style="float: right; display: flex; line-height: 50px;">
                    <div style="float: right;">
                        选中 <span style="font-size: 14px; color: red;">{{totalNumber}}</span> 件商品</div>
                    <div style="float: right; margin-right: 10px;">
                        总价（不含邮费）： <span style="font-size: 14px; color: red;">{{totalMoney()}}</span> 元</div>
                    <div class="car-operation-total-button" @click="count">
                        结 算
                    </div>
                </div>
            </div>

        </div>

        <div v-if="activeStep === 1">
            
            <el-row style="margin-bottom: 10px;">
                <el-col :span="6" :key="index" style="padding: 5px;"
                    v-for="(item, index) in addressList">
                    <div class="address-card" @click="addressActive = index"
                        :style="addressActive === index?'background-color: #ddd;':''">
                        {{item.contact}} 收<br/>
                        {{item.address}} {{item.phone}}
                        <i v-if="addressActive === index" class="el-icon-success"/>
                    </div>
                </el-col>
            </el-row>

            <div v-for="(item, index) in orderItems"
                :key="index" class="talbe-content">
                <div class="talbe-content-item" style="width: calc(100% - 320px);">
                    <el-image :src="item.image" fit="fill"
                        style="width: 80px; height: 80px; float: left;"/>
                    <div style="float: left; margin-left: 20px; width: calc(100% - 80px - 20px)">{{item.name}}</div>
                </div>
                <div class="talbe-content-item" style="width: 100px;">
                    {{item.price}}
                </div>
                <div class="talbe-content-item" style="width: 120px;">
                    {{item.num}}
                </div>
                <div class="talbe-content-item" style="width: 100px;">
                    {{totalPrice(item)}}
                </div>
            </div>

            <div class="car-operation">
                <div style="float: right; display: flex; line-height: 50px;">
                    <div class="car-operation-total-button" @click="confirmOrder">
                        确认下单
                    </div>
                </div>
            </div>

        </div>

        <div v-if="activeStep === 2" style="text-align: center;">
            下单成功！
            <div v-if="payCode">
                <div style="margin-bottom: 10px; font-size: 14px;">
                    请使用微信扫一扫支付</div>
                <qrcode-vue :value="payCode"  size="200"/>
            </div>
        </div>

    </div>
</template>

<script>

import QrcodeVue from 'qrcode.vue'

export default {
    name: 'Home',
    components: {
        QrcodeVue,
    },
    data() {
        return {
            activeStep: 0,
            shopCarList: [], // 购物车列表
            orderItems: [], // 订单项
            addressList: [],
            addressActive: null,
            allChecked: false,
            num: 1,
            payCode: '', //
            url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
        }
    },
    created() {
        this.loadShopCarList();
        this.loadOrderAddressList();
    },
    computed: {
        totalNumber() {
            return this.getChecked().length;
        }
    },
    methods: {
        allCheckedChange(val) {
            let shopCarList = JSON.parse(JSON.stringify(this.shopCarList));
            shopCarList.map(item=> {
                item.display = val;
                return item;
            });
            this.shopCarList = shopCarList;
        },
        itemChange() {
            if(this.shopCarList.length ===
                this.getChecked().length) {
                this.allChecked = true;
            } else  { this.allChecked = false; }
        },
        numberChange(val, val2, item) {
            item.display = true;
            item.num--;
            let num = val - val2;

            let params = '/'+item.skuId+'/'+num;
            this.$getAction(this.$apiUrl.shopCarAdd+params)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code === '2000') { reject(res.msg?res.msg:'响应错误'); return; }
                    this.$message.success('操作成功');
                    item.num++;
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error);  });
        },
        totalPrice(item) {
            return item.price * item.num;
        },
        totalMoney() {
            let totalMoney = 0;
            this.getChecked().forEach(item=> {
                totalMoney += item.price * item.num;
            });
            return totalMoney;
        },
        getChecked() {
            let checkeds = this.shopCarList.filter(item=> {
                return item.display; });
            return checkeds?checkeds:[];
        },
        del(item) {
            this.$confirm('确认将删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.actionDel([item.skuId]);
            });
        },
        batchDel() {
            let delProducts = this.totalNumber;
            if(delProducts === 0) {
                this.$message.info('请选择要删除的商品！');
                return;
            }
            this.$confirm('确认将删除选中的'+delProducts+'件商品吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let ids = [];
                let shopCarList = this.shopCarList;
                for (let i = 0; i < shopCarList.length; i++) {
                    const item = shopCarList[i];
                    if(item.display) {
                        ids.push(item.skuId);
                    }
                }
                this.actionDel(ids);
            });
        },
        loadShopCarList() {
            let params = '/'+1+'/'+10;
            this.$getAction(this.$apiUrl.shopCarList+params)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.msg?res.msg:'响应错误'); return; }

                    let newData = [];
                    let data = res.data;
                    if(data) { newData = data; }
                    this.shopCarList = newData;
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
        },
        loadOrderAddressList() {
            this.$getAction(this.$apiUrl.orderAddressList)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.msg?res.msg:'响应错误'); return; }

                    let newData = [];
                    let data = res.data;
                    if(data) { newData = data; }
                    this.addressList = newData;
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
        },
        actionDel(ids) {
            let params = ids;
            console.log('params ------- ', params);
            this.$deleteAction(this.$apiUrl.shopCarDel, params)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.message?res.message:'响应错误'); return; }
                    this.$message.success('操作成功');
                    this.loadShopCarList();
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
        },
        clearCat() {
            this.$deleteAction(this.$apiUrl.shopCarClear)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.message?res.message:'响应错误'); return; }
                    this.$message.success('操作成功');
                    this.loadShopCarList();
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
            
        },
        // 结算
        count() {
            this.orderItems = this.getChecked();
            this.activeStep++;
        },
        // 确认下单
        confirmOrder() {
            let items = [];
            this.orderItems.find(item=> {
                let newItem = { skuId: item.skuId, num: item.num };
                items.push(newItem);
            });

            let address = this.addressList[this.addressActive];
            let pathParams = '/'+address.id;
            let params = items;

            this.$postAction(this.$apiUrl.orderManageAdd+pathParams, params)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.msg?res.msg:'响应错误'); return; }

                    this.$message.success('操作成功');
                    this.activeStep++;
                    this.pay(res.data);
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
        },
        pay(orderNo) {
            let pathParams = '/'+orderNo;

            this.$getAction(this.$apiUrl.orderManagePay+pathParams)
            .then(res=> {
                return new Promise((resolve, reject)=> {
                    if(!res || !res.code) { reject('响应错误'); return; }
                    if(res.code != '20000') { reject(res.msg?res.msg:'响应错误'); return; }

                    let data = res.data;
                    if(!data) { reject('响应错误'); return; }

                    if(data.result_code !== 'SUCCESS') {
                        reject('请求支付失败'); return;
                    }

                    this.payCode = data.code_url;
                    resolve();
                });
            }).catch(error=>{ console.error(error); this.$message.error(error); });
        },
    }
}
</script>

<style scoped>
    .talbe-title {
        width: 100%;
        display: flex;
        line-height: 30px;
        background-color: #eaeaea;
        margin-bottom: 10px;
    }

    .talbe-title-item {
        padding: 0 10px;
    }

    .talbe-content {
        line-height: 24px;
        width: 100%; display: flex;
        background-color: #f9f9f9;
        padding: 10px 0;
        margin-bottom: 10px;
    }
    .talbe-content-item {
        padding: 0 10px;
    }

    .car-operation {
        width: 100%;
        height: 50px;
        background-color: #f9f9f9;
    }
    .car-operation-total-button {
        height: 50px;
        line-height: 50px;
        width: 100px;
        text-align: center;
        font-size: 18px;
        color: white;
        cursor: pointer;
        float: right;
        background-color: #bbbbbb;
    }
    .car-operation-total-button:hover {
        background-color: #ccc;
    }
    .car-operation-total-button:active {
        background-color: #bbbbbb;
    }

    .address-card {
        height: calc(100% - 20px); width: calc(100% - 20px);
        background-color: #eee; padding: 10px; font-size: 14px;
        line-height: 25px;
    }

    .address-card:hover {
        background-color: #ddd;
    }
</style>